<template>
	<!-- 事件查询组件 -->
	<div id="container">
		<div>
			<!-- 下拉菜单 -->
			<el-dropdown
				:class="isChosen == true ? 'chosen' : ''"
				trigger="click"
				@command="handleCommand"
			>
				<span class="el-dropdown-link title">
					事件查询
					<i class="el-icon-arrow-down el-icon--right"></i>
				</span>
				<el-dropdown-menu slot="dropdown">
					<el-dropdown-item command="on" :disabled="serchBtnState">
						<img src="img/查询统计.png" alt="" />
						拉框查询
					</el-dropdown-item>
					<el-dropdown-item command="off">
						<img src="img/关闭_操作_jurassic.png" alt="" />
						关闭查询
					</el-dropdown-item>
				</el-dropdown-menu>
			</el-dropdown>
			<!--------------------------------------------- 事件表格弹窗 -------------------------------------------------------->
			<el-dialog
				title="拉框查询结果"
				v-el-drag-dialog
				:visible.sync="dialogTableVisible"
				width="60%"
				:modal="false"
				:before-close="handleClose"
				:close-on-click-modal="false"
				center
			>
				<!-- -----------------------------------事件统计弹窗(嵌套的弹窗)------------------------------------- -->
				<el-dialog
					class="innerDialog"
					v-el-drag-dialog
					width="550px"
					:visible.sync="innerVisible"
					:close-on-click-modal="false"
					append-to-body
				>
					<el-card class="statistics-card">
						<div slot="header" class="clearfix">
							<h2>事件统计图</h2>
						</div>
						<div>
							<el-button
								type="success"
								:class="!isPieOrColumnar ? 'currentPie' : ''"
								@click="showColumnar"
							>
								按月份统计
							</el-button>
							<el-button
								type="success"
								:class="isPieOrColumnar ? 'currentPie' : ''"
								@click="showPie"
							>
								按类型统计
							</el-button>
						</div>
						<!-- 饼状图 -->
						<div
							v-show="isPieOrColumnar"
							style="width: 450px; height: 450px"
							class="echerts-type"
						></div>
						<!-- 柱状图 -->
						<div
							v-show="!isPieOrColumnar"
							style="width: 450px; height: 450px"
							class="echerts-month"
						></div>
					</el-card>
				</el-dialog>
				<!-- ----------------------------------------------------------------------------------------------------------- -->
				<!-- 事件展示表格 -->
				<el-collapse value="1" accordion>
					<el-collapse-item name="1">
						<template slot="title">
							<!-- 顶栏导航条 -->
							<div class="nav-event">
								<!-- 生成事件热力图组件 -->
								<EventHeatMap class="heatMap"></EventHeatMap>
								<el-button type="primary" @click.stop="showStatisticsBox">
									生成事件统计图
								</el-button>
							</div>
						</template>
						<el-table class="table-content" :data="showEventData" border>
							<el-table-column
								prop="eventNum"
								label="事件编号"
								sortable
								width="150"
							></el-table-column>
							<el-table-column
								prop="eventType"
								label="事件类型"
								width="100"
							></el-table-column>
							<el-table-column label="事件等级" width="100">
								<template slot-scope="scope">
									<p
										:class="{
											Level1: scope.row.eventLevel == 1,
											Level2: scope.row.eventLevel == 2,
											Level3: scope.row.eventLevel == 3,
											Level4: scope.row.eventLevel == 4,
										}"
									>
										{{ scope.row.eventLevel | toEventLevel }}
									</p>
								</template>
							</el-table-column>
							<el-table-column
								prop="eventTime"
								label="发生时间"
								sortable
								width="150"
							></el-table-column>
							<el-table-column
								prop="eventPlace"
								label="发生地点"
							></el-table-column>
							<el-table-column
								prop="cartNum"
								label="车牌号"
								width="120"
							></el-table-column>
							<el-table-column
								prop="driver"
								label="驾驶员"
								width="120"
							></el-table-column>
							<el-table-column label="处理状态" width="80">
								<template slot-scope="scope">
									<p
										:class="{
											todo: scope.row.sloveState == 0,
											doing: scope.row.sloveState == 1,
											done: scope.row.sloveState == 2,
										}"
									>
										{{ scope.row.sloveState | toEventSlove }}
									</p>
								</template>
							</el-table-column>
						</el-table>
						<!-- 分页器 -->
						<div class="page-box">
							<el-pagination
								@size-change="handleSizeChange"
								@current-change="handleCurrentChange"
								:current-page="this.page"
								:page-sizes="[3, 5, 10]"
								:page-size="100"
								layout="total, sizes, prev, pager, next, jumper"
								:total="this.total"
							></el-pagination>
						</div>
					</el-collapse-item>
				</el-collapse>
			</el-dialog>
		</div>
	</div>
</template>

<script>
import { mapState } from 'vuex';
import { createDraw } from '../../../../utils/Draw';
import { Query } from '../../../../utils/Query'; //引入封装的查询函数
import * as echarts from 'echarts'; //引入echarts
import EventHeatMap from './EventHeatMap.vue'; //导入热力图组件
import elDragDialog from '../../../directive/el-dragDialog'; //导入自定义弹窗拖拽
// ------------------------新建画笔图层-----------------------------------------------------------------
var source = new ol.source.Vector({
	wrapX: false,
}); //实例化数据源
var layer = new ol.layer.Vector({
	source: source,
}); //实例化矢量图层
var draw = null; //创建画笔
// ------------------------新建标注图层---------------------------------
var sourceEvent = new ol.source.Vector({
	wrapX: false,
});
var layerEvent = new ol.layer.Vector({
	source: sourceEvent,
	style: new ol.style.Style({
		image: new ol.style.Icon({
			anchor: [0.5, -2],
			anchorOrigin: 'bottom-right',
			anchorXUnits: 'fraction',
			anchorYUnits: 'pixels',
			offsetOrigin: 'top-right',
			// offset:[0,10],
			//图标缩放比例
			scale: 1,
			//透明度
			opacity: 1,
			//图标的url
			src: '../../../../src/assets/img/accident.png',
		}),
	}),
});
export default {
	name: 'QueryEvent',
	directives: {
		// 自定义拖拽弹窗配置
		elDragDialog,
	},
	components: { EventHeatMap },
	data() {
		return {
			isChosen: false, //是否激活查询菜单
			eventData: [], //查询到的所有事件数据
			showEventData: [], //显示在表格的事件数据
			dialogTableVisible: false, //控制事件查询弹窗
			innerVisible: false, //控制统计图表弹窗
			isPieOrColumnar: true, //控制显示柱状图还是饼状图
			echarts_month: [], //柱状图月份数据
			serchBtnState: false, //控制查询按钮是否禁用
			total: 0, //事件总条数
			page: 1, //当前页码数
			size: 3, //每页显示数
			activeNames: '1',
			pieDataEvent: [], //饼状图数据
		};
	},
	computed: {
		...mapState(['map', 'docLayer', 'isHeatMap']),
	},
	filters: {
		// 用过滤器将事故等级从代号解译成文字
		toEventLevel: (value) => {
			if (value == 1) {
				value = '轻微事故';
			} else if (value == 2) {
				value = '一般事故';
			} else if (value == 3) {
				value = '重大事故';
			} else {
				value = '特大事故';
			}
			return value;
		},
		// 用过滤器将事故处理情况从代号解译成文字
		toEventSlove: (value) => {
			if (value == 0) {
				value = '待处理';
			} else if (value == 1) {
				value = '处理中';
			} else if (value == 2) {
				value = '已归档';
			}
			return value;
		},
	},
	watch: {
		isHeatMap: function (n, o) {
			if (n == true) {
				// 若在热力图页面则移除标注图层
				this.map.removeLayer(layerEvent); //移除查询标注图层
			} else {
				// 否则添加标注图层
				this.map.addLayer(layerEvent); //移除查询标注图层
			}
		},
	},
	// -----------------------------------------------------方法-------------------------------------------------
	methods: {
		//----------开启查询---------------
		handleCommand(command) {
			if (command == 'on') {
				this.DrawActive();
				this.isChosen = true; //激活查询菜单
			} else {
				this.handleClose();
				this.isChosen = false; //关闭查询菜单
			}
		},
		// ------------拉框查询------------
		DrawActive() {
			draw = createDraw({
				type: 'Box', //矩形
				source: source,
				callback: this.handleDraw,
			});
			this.map.addInteraction(draw);
		},
		handleDraw(e) {
			source.clear();
			this.map.removeLayer(layerEvent); //每次查询前移除标注图层，以防重复
			this.eventData = []; //每次拉框查询之前都要清空数据
			const geom = e.feature.getGeometry();
			// console.log(geom);
			const service = { docName: 'guanggu', layerId: 2 };
			Query.queryByGeom({
				geom,
				service,
				callback: this.querySuccess,
			});
		},
		querySuccess(result) {
			console.log(result);
			if (result.TotalCount == 0) {
				this.$message.error('该区域不存在事件，请重新查询');
				return;
			}
			//初始化Zondy.Format.PolygonJSON类
			// console.log(result);
			var format = new Zondy.Format.PolygonJSON();
			//将MapGIS要素JSON反序列化为ol.Feature类型数组
			var features = format.read(result);

			sourceEvent.addFeatures(features);
			this.map.addLayer(layerEvent);
			// console.log(features);
			// 获取查询到的事件总数
			this.total = features.length;
			// console.log(features);
			// console.log(features[0].id_); //fid
			// console.log(features[0].values_.values_.事件编号); //事件编号
			//遍历features存储到eventData数据中
			features.forEach((item) => {
				// 遍历获取时间，数组格式化处理
				this.eventData.push({
					eventNum: item.values_.values_.事件编号,
					eventType: item.values_.values_.事件类型,
					eventLevel: item.values_.values_.事件等级,
					eventTime: item.values_.values_.发生时间,
					eventPlace: item.values_.values_.发生地点,
					cartNum: item.values_.values_.车牌号,
					driver: item.values_.values_.驾驶员,
					sloveState: item.values_.values_.处理状态,
				});
			});
			this.serchBtnState = true; //关闭查询按钮，防止重复查询
			this.map.removeInteraction(draw); //每次拉框查询结束，清空画笔
			// this.showTableState = true; //显示事件查询表格
			this.dialogTableVisible = true;
			this.handleSizeChange(this.size); //解决第一页不显示问题
		},
		// 关闭查询
		handleClose() {
			this.dialogTableVisible = false; //关闭弹窗
			this.map.removeInteraction(draw); //移除画笔
			this.map.removeLayer(layerEvent); //移除查询标注图层
			this.serchBtnState = false; //查询按钮
			this.eventData = []; //查询数据清空
			this.isChosen = false; //关闭菜单
		},
		// ------------------------------------分页相关方法-----------------------------------------
		// 改变每页显示数目
		handleSizeChange(val) {
			this.size = val;
			const start = (this.page - 1) * this.size; //起始下标（包含）
			const end = (this.page - 1) * this.size + this.size; //结束下标（不包含）
			this.showEventData = this.eventData.slice(start, end);
		},
		// 翻页
		handleCurrentChange(val) {
			this.page = val;
			const start = (this.page - 1) * this.size; //起始下标（包含）
			const end = (this.page - 1) * this.size + this.size; //结束下标（不包含）
			this.showEventData = this.eventData.slice(start, end);
		},
		// ---------------------------------------统计图表相关方法--------------------------------------------------------
		// 显示统计图表
		showStatisticsBox() {
			this.innerVisible = true;
			// setTimeout 可以延迟调用函数，防止dom没生成就操作dom报错
			setTimeout(() => {
				this.echartsInit1();
			}, 300);
		},

		// 显示柱状图，隐藏饼状图
		showColumnar() {
			this.isPieOrColumnar = false;
			this.getMonthData();
			setTimeout(() => {
				this.echartsInit2();
			}, 300);
		},
		// 显示饼状图，隐藏柱状图
		showPie() {
			this.isPieOrColumnar = true;
			this.echartsInit1();
		},
		// 获取按月份统计时间数
		getMonthData() {
			console.log('获取统计月份数据成功');
			let MonthData = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
			this.eventData.forEach((item1) => {
				if (item1.eventTime.slice(0, 4) == '2018') {
					// console.log(item1.eventTime.split('.')[1]);
					MonthData.forEach((item2, index) => {
						if (item1.eventTime.split('.')[1] == index + 1) {
							// console.log(Number(item1.eventTime.split('.')[1]));
							MonthData[index]++;
						}
					});
				}
				this.echarts_month = MonthData;
			});
		},

		// 饼状图
		echartsInit1() {
			// 获取饼状图的数据
			const pieData = [
				{ name: '碰撞', value: 0 },
				{ name: '碾压', value: 0 },
				{ name: '翻车', value: 0 },
				{ name: '失火', value: 0 },
				{ name: '刮擦', value: 0 },
				{ name: '其他', value: 0 },
			];
			pieData.forEach((item1) => {
				this.eventData.forEach((item2) => {
					if (item1.name == item2.eventType) {
						item1.value++;
					}
				});
			});
			this.pieDataEvent = pieData;

			echarts.init(document.querySelector('.echerts-type')).setOption({
				title: {
					text: '事件类型分布统计图',
					subtext: '数据实时更新',
					left: 'center',
				},
				tooltip: {
					trigger: 'item',
				},
				legend: {
					orient: 'vertical',
					bottom: 'bottom',
				},
				graphic: {
					type: 'text',
					left: '30%',
					bottom: '6%',
					style: {
						text: `交通事件共${this.total}起`,
						fontSize: 20,
						color: '#acf',
					},
				},
				toolbox: {
					show: true,
					feature: {
						dataView: { show: true, readOnly: false },
						restore: { show: true },
						saveAsImage: { show: true },
					},
				},
				series: [
					{
						type: 'pie',
						radius: '50%',
						data: this.pieDataEvent,
						label: {
							position: 'outer',
							formatter: '{b}:\r{c}\r条' + '\n\r' + '({d}%)',
						},
						emphasis: {
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0.5)',
							},
						},
					},
				],
			});
		},
		// 柱状图
		echartsInit2() {
			// 柱状图
			echarts.init(document.querySelector('.echerts-month')).setOption({
				title: {
					text: '2018年各个月份事件统计情况',
					subtext: '数据实时更新',
					left: 'center',
				},
				xAxis: {
					type: 'category',
					data: [
						'一月',
						'二月',
						'三月',
						'四月',
						'五月',
						'六月',
						'七月',
						'八月',
						'九月',
						'十月',
						'十一月',
						'二月',
					],
				},
				yAxis: {
					type: 'value',
				},
				graphic: {
					type: 'text',
					left: '30%',
					bottom: '3%',
					style: {
						text: `交通事件共${this.total}起`,
						fontSize: 20,
						color: '#acf',
					},
				},
				toolbox: {
					show: true,
					feature: {
						dataView: { show: true, readOnly: false },
						restore: { show: true },
						saveAsImage: { show: true },
					},
				},
				series: [
					{
						data: this.echarts_month,
						type: 'bar',
						showBackground: true,
						backgroundStyle: {
							color: 'rgba(180, 180, 180, 0.2)',
						},
						markPoint: {
							simbol: 'pin',
							simbolSize: 50,
							itemStyle: {
								color: 'red',
							},
							data: [
								{
									type: 'max',
									name: '最大值',
									color: 'red',
								},
								{
									type: 'min',
									name: '最小值',
								},
							],
						},
						markLine: { data: [{ type: 'average', name: '平均值' }] },
					},
				],
			});
		},
	},
};
</script>

<style scoped>
.chosen {
	/* 激活菜单显示的样式 */
	background-color: antiquewhite !important;
	color: darkcyan !important;
}
.el-dropdown {
	z-index: 11;
	padding: 0 5px;
	border-radius: 10px;
	border-bottom: 2px solid white;
	background-color: rgba(248, 248, 132, 0.7);
	display: flex;
	justify-content: center;
	align-items: center;
}
.title {
	font-size: 18px;
}
.el-dropdown:hover {
	cursor: pointer;
	font-weight: 900;
	background-color: antiquewhite;
	color: darkcyan;
	box-shadow: 1px 1px 0px 0px;
	transition: all 0.2s ease-in-out;
}
.el-dropdown-menu {
	background-color: whitesmoke;
	font-weight: 900;
}
.nav-event {
	margin: 5px 0;
	width: 100%;
	align-items: center;
	background: #ffffff;
	overflow: hidden;
}
.nav-event button {
	margin-left: 20px;
	border-radius: 5px;
}

/* 分页 */
.page-box {
	margin: 5px auto;
	text-align: center;
	background: rgba(172, 174, 175, 0.1);
}

/* 查看事件状态样式 */
.todo {
	padding: 0 5px;
	text-align: center;
	background: rgb(170, 14, 14);
	color: white;
}
.doing {
	padding: 0 5px;
	text-align: center;
	background: rgb(201, 137, 20);
	color: white;
}
.done {
	padding: 0 5px;
	text-align: center;
	background: rgb(16, 48, 155);
	color: white;
}
/* 查看事件等级样式 */
.Level1 {
	padding: 0 5px;
	text-align: center;
	color: green;
	font-weight: 600px;
	border: 2px solid green;
}
.Level2 {
	padding: 0 5px;
	text-align: center;
	color: rgb(21, 141, 189);
	font-weight: 600px;
	border: 2px solid rgb(21, 141, 189);
}
.Level3 {
	padding: 0 5px;
	text-align: center;
	color: blue;
	font-weight: 600px;
	border: 2px solid blue;
}
.Level4 {
	padding: 0 5px;
	text-align: center;
	color: red;
	font-weight: 600px;
	border: 2px solid red;
}
.heatMap {
	float: left;
}

/* 统计图表按钮 */
.currentPie {
	background: rgb(7, 78, 170);
	border: 2px solid red;
}
</style>
